<?php
/**
 * Created by PhpStorm.
 * User: buddha
 * Date: 2021/6/18
 * Time: 14:42
 */

namespace app\admin\controller;


use app\admin\service\ManagerService;
use app\BaseController;
use app\utils\Token;
use think\facade\Cache;
use think\facade\Config;

class Account extends BaseController
{
    /**
     * @var $service ManagerService
     */
    protected $service;

    public function initialize()
    {
        parent::initialize();
        $this->service = new ManagerService();
    }

    /**
     * 用户登陆
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save() {
        $row = $this->service->login(request()->data);
        if (empty($row)) {
            return fail('账号或密码错误');
        }
        // 生成token
        $token = Token::getToken(['username' => $row['username'], 'id' => $row['id']]);
        // 信息更新
        $this->service->update($row['id'], ['login_times' => $row['login_times'] + 1, 'last_login_ip' => getIp(), 'update_time' => time()]);
        // token缓存起来
        Cache::set('token_admin_' . $row['id'], $token, Config::get('token')['exp']);
        return success('ok', ['token' => $token, 'username'=>$row['username'], 'id' => $row['id']]);
    }

    /**
     * 用户退出
     * @return \think\response\Json
     */
    public function create() {
        Cache::delete('token_admin_' . request()->userInfo->id);
        return success('退出成功');
    }
}